from django.shortcuts import render_to_response
from myproject.auth.models import User, Update, ThreadNotification
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm
import datetime

'''
author: Nader Alexan
date: 01.04.12
desc: direct to admin's homepage
''' 
def admin(request):
    updates = Update.objects.filter(admin_update=True).order_by('-pub_date')
    return render_to_response('admins/admin.html', {'updates':updates}, context_instance=RequestContext(request))

'''
author: Nader Alexan
date: 03.04.12
desc: take data from form and create a new admin
'''
def createAdmin(request):
    # Putting the import at the begining of this script seems to produce a "could not import" error everywhere 
    from myproject.reg.views import emailValidation
    success_message, email_error = None, None
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        email = request.POST['email']
        email_error = emailValidation(email)
        if form.is_valid() and not email_error:
            User.objects.create_superuser(form.cleaned_data['username'], email, form.cleaned_data['password2'])
            success_message = 'New admin ('+form.cleaned_data['username']+') created successfully'
            return render_to_response('admins/createAdmin.html', {'form':UserCreationForm(), 'success_message':success_message, 'email_error':None}, context_instance=RequestContext(request))
    else:
        form = UserCreationForm()
    return render_to_response('admins/createAdmin.html', {'form':form, 'success_message':success_message, 'email_error':email_error}, context_instance=RequestContext(request))


'''
author: Nader Alexan
date: 03.04.12
desc: Allow admin to change their password
'''
def changePassword(request):
    from myproject.auth.views import changePassword
    return changePassword(request, 'admins/changePassword.html')

'''
author: Nader Alexan
date: 06.04.12
desc: Allow admin to post updates
'''
def postUpdateAdmin(request):
    from myproject.myprofile.views import postUpdate
    return postUpdate(request)

'''
author: Nader Alexan
date: 09.04.12
desc: Get a comma sperated string with all the usernames to be banned and the reason for banning them and ban them
'''
def banUsers(request):
    from myproject.messaging.views import getUsernamesNids
    from myproject.auth.models import AbstractUser
    success_message = None
    usernames = getUsernamesNids(AbstractUser.objects.all())
    if request.method == 'POST':
        users = request.POST['as_values_users']
        reason_text = request.POST['reason_text']
        reason_choice = request.POST['reason_choice']
        banned = ''
        
        counter = 0
        for user in users.split(','):
            if user != '':
                counter += 1
                current_user = AbstractUser.objects.get(pk=int(user))
                current_user.banned = True
                if reason_choice != 'other':
                    current_user.banning_reason = reason_choice
                else:
                    current_user.banning_reason = reason_text
                current_user.save()
                banned += current_user.user.username + ', '
        if counter > 1:
            success_message = 'The users with usernames: ' + banned[0:len(banned)-2] + ' have been successfully banned'
        else:
            success_message = 'The user with username: ' + banned[0:len(banned)-2] + ' has been successfully banned'
    return render_to_response('admins/banUsers.html', {'success_message':success_message,
                                                       'usernames':usernames}, context_instance=RequestContext(request))
    
def unbanUsers(request):
    from myproject.messaging.views import getUsernamesNids
    from myproject.auth.models import AbstractUser
    success_message = None
    usernames = getUsernamesNids(AbstractUser.objects.all())
    if request.method == 'POST':
        users = request.POST['as_values_users']
        unbanned = ''
        
        counter = 0
        for user in users.split(','):
            if user != '':
                counter += 1
                current_user = AbstractUser.objects.get(pk=int(user))
                current_user.banned = False
                current_user.save()
                unbanned += current_user.user.username + ', '
        if counter > 1:
            success_message = 'The users with usernames: ' + unbanned[0:len(unbanned)-2] + ' have been successfully unbanned'
        else:
            success_message = 'The user with username: ' + unbanned[0:len(unbanned)-2] + ' has been successfully unbanned'
    return render_to_response('admins/unbanUsers.html', {'success_message':success_message,
                                                       'usernames':usernames}, context_instance=RequestContext(request))
'''
author: Nader Alexan
date: 10.02.12
desc: Show current people in HOF and allow admin to add or remove people from HOF
'''
def modifyHOF(request):
    from myproject.auth.models import Teacher, Institute, Student
    from myproject.messaging.views import getUsernamesNids
    
    if request.method == 'POST':
        try:
            remove = request.POST['as_values_remove']
            toggleHOF(remove)
        except: pass
        
        try:
            add = request.POST['as_values_add']
            toggleHOF(add)
        except: pass
    
    can_be_added = getAbstractUsers(Student.objects.filter(HOF=False))
    [can_be_added.append(ele) for ele in getAbstractUsers(Teacher.objects.filter(HOF=False))]
    [can_be_added.append(ele) for ele in getAbstractUsers(Institute.objects.filter(HOF=False))]
    if can_be_added: can_be_added =  getUsernamesNids(can_be_added)
    
    can_be_removed = getAbstractUsers(Student.objects.filter(HOF=True))
    [can_be_removed.append(ele) for ele in getAbstractUsers(Teacher.objects.filter(HOF=True))]
    [can_be_removed.append(ele) for ele in getAbstractUsers(Institute.objects.filter(HOF=True))]
    if can_be_removed: can_be_removed = getUsernamesNids(can_be_removed)
    
    return render_to_response('admins/modifyHOF.html', {'students':Student.objects.filter(HOF=True),
                                                       'teachers':Teacher.objects.filter(HOF=True),
                                                       'institutes':Institute.objects.filter(HOF=True),
                                                       'can_be_added':can_be_added,
                                                       'can_be_removed':can_be_removed}, context_instance=RequestContext(request))
'''
author: Nader Alexan
date: 10.04.12
desc: Toggle the boolean value of HOF for a set usernames seperated by commas
'''
def toggleHOF(ids_csv):
    from myproject.myprofile.views import getUser
    from myproject.auth.models import AbstractUser
    for _id in ids_csv.split(','):
        if _id != '':
            currentUser = getUser(AbstractUser.objects.get(pk=_id), abstract=True)
            currentUser.HOF = not currentUser.HOF
            currentUser.save()
            
'''
author: Nader Alexan
date: 10.04.12
desc: Get Abstract Users given Teachers/Institutes/Students
'''
def getAbstractUsers(users):
    return [user.abstract_user for user in users]

'''
author: Nader Alexan
date: 12.04.12
desc: Allow the admin to go through the reported reviews
'''
def checkReportedReviews(request):
    from myproject.auth.models import Review
    reported = Review.objects.exclude(report_count=0)
    return render_to_response('admins/reportedReviews.html', {'reported':reported,
                                                              }, context_instance=RequestContext(request))
'''
author: Nader Alexan
date: 12.04.12
desc: Allow admin to delete or unreport reported reviews. If deleted then send a msg to review owner informing him/her of the reason why
'''
def modifyReportedReviews(request, review_id):
    from myproject.auth.models import Review, Thread, MSG
    reported = Review.objects.exclude(report_count=0)
    action = request.POST['action']
    reason_text = request.POST['reason_text']
    reason_choice = request.POST['reason_choice']
    review = Review.objects.get(pk=review_id)
    if action == 'keep':
        review.report_count = 0
        review.save()
        success_message = 'The review has been successfully unreported'
    else:
        reviewer = review.reviewer
        reviewee = review.reviewee
        date = review.date
        review.delete()
        
        #send a msg to sender informing them of this action
        thread = Thread(subject='Concerning one of your reviews', date_started=datetime.datetime.now(), admin=True)
        thread.save()
        thread.receivers.add(reviewer)
        thread.save()
        
        content = 'The review that you posted about ' + reviewee.user.username + ' on ' + str(date) + ' has been deleted by one of the admins'
        if reason_choice != 'other': content += ' because of the following reason(s): ' + reason_choice
        elif reason_text: content += ' because of the following reason(s): ' + reason_text
        else: content += '.'  
        
        msg = MSG(thread=thread, date_sent=datetime.datetime.now(), content=content)
        msg.save()

        ThreadNotification(thread=thread, abstract_user=reviewer, notifications=1).save()
        reviewer.messages_notification += 1
        reviewer.save()
        
        success_message = 'The review has been successfully deleted and the responsible user has been informed'
        
    return render_to_response('admins/reportedReviews.html', {'reported':reported,
                                                              'success_message':success_message,
                                                              }, context_instance=RequestContext(request))

def manageActivationCodes(request):
    from myproject.auth.models import ActivationCode
    success_message, failure_message = None, None
    if request.POST:
        code = request.POST['code']
        if ActivationCode.objects.filter(code=code):
            failure_message = "This activation code is already used."
        elif len(code) > 5:
            failure_message = "Activation code cannot be longer than 5 characters long."
        else:
            ActivationCode(code=code, abstract_user=None).save()
            success_message = "Activation code successfully added"

    usedCodes = ActivationCode.objects.exclude(abstract_user=None)
    unusedCodes = ActivationCode.objects.filter(abstract_user=None)

    return render_to_response('admins/manageActivationCodes.html', {'usedCodes':usedCodes,
                                                                    'unusedCodes':unusedCodes,
                                                                    'success_message':success_message,
                                                                    'failure_message':failure_message,
                                                                    }, context_instance=RequestContext(request))


